import csv


def append_to_csv(name, thrift_port, filename="data.csv"):
    """将 name 和 thrift_port 追加到 CSV 文件"""
    try:
        with open(filename, "a", newline="") as csvfile:
            fieldnames = ["name", "thrift_port"]
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

            # 如果文件为空，写入表头
            if csvfile.tell() == 0:
                writer.writeheader()

            # 写入数据
            writer.writerow({"name": name, "thrift_port": thrift_port})
    except Exception as e:
        print(f"追加数据时出错: {e}")


def read_from_csv(filename="data.csv"):
    """从 CSV 文件读取内容到列表"""
    data = []
    try:
        with open(filename, "r") as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                data.append((row["name"], int(row["thrift_port"])))
        return data
    except FileNotFoundError:
        print(f"错误：文件 {filename} 不存在")
        return []
    except Exception as e:
        print(f"读取数据时出错: {e}")
        return []
